# -*- coding: utf-8 -*-
import os,sys,json
from pyserver.contrib.redis_cache import RedisManage

class LocalResource:


	def __init__(self):
		self.__initLocalResource()
		
	@staticmethod
	def getResources(key):
		localDict = RedisManage.getCacheDict('__LocalResources_Cache')
		return Dictate(localDict.get(key))

	'''
	@classmethod
	def setLanguageKey(self,resKey):
		self._languageKey = resKey
	'''

	def __initLocalResource(self):
		localDict = {}
		basePath = './pyserver/local/'
		fileList = os.listdir(basePath)
		for f in fileList:
			fpath = basePath + f
			if os.path.isfile(fpath) and f.endswith('.strings'):
				self.__parseFile(fpath,f,localDict)

		#客户端js资源不缓存，直接输出至客户端
		clientRes = {}
		for key in localDict.keys():
			clientRes[key] = localDict[key].pop("clientResource")
		self.__writeLocalResource(clientRes)

		RedisManage.setCacheDict("__LocalResources_Cache",localDict,0)
		

	def __writeLocalResource(self,localDict):
		basePath = './pyserver/static/scripts/local/'

		for key in localDict:
			if not os.path.exists(basePath): 
				os.mkdir(basePath)
			fileName = '%s/etlinking.resources_%s.js' % (basePath,key)
			# 如果文件已存在,则不生成
			#if os.path.exists(fileName):
			#	continue

			fsock = open(fileName, "w")
			fsock.write('nsbase.resources.repository({"clientResource":')
			#fsock.write('nsbase.config.resource_%s = ' % key)$.extend(true, {}, nsbase.enums,{"CampaignStatusEnum":
			#fsock.write(str(localDict[key]).decode("utf-8"))
			fsock.write(json.dumps(localDict[key],ensure_ascii=False))
			fsock.write('});\n')
			fsock.write('nsbase.resources.rebuildObject();')
			fsock.close()

	def __parseFile(self,fpath,fileName,localDict):
		startIndex = fileName.find('_') + 1
		endIndex = fileName.find('.')
		localKey = fileName[startIndex:endIndex]
		localDict[localKey] = {}

		fsock = open(fpath,'r')
		while True:
			lines = fsock.readlines(100000)
			if not lines:
				break
			for line in lines:
				line = line.strip('\r\n')
				if (len(line) == 0) or (line.lstrip().startswith('#')):
					continue

				items = line.split('\t')
				if len(items) == 1:
					curDict = {}
					localDict[localKey][items[0]] = curDict
					continue

				if len(items) == 2:
					tmpStr = items[1]
					if len(tmpStr.strip()) == 0:
						continue
						
					tmpArray = tmpStr.split(' = ')
					curDict[tmpArray[0].strip()] = tmpArray[1].strip()

	
class Dictate(object):
	"""Object view of a dict, updating the passed in dict when values are set
	or deleted. "Dictate" the contents of a dict...: """

	def __init__(self, d):
		# since __setattr__ is overridden, self.__dict = d doesn't work
		object.__setattr__(self, '_Dictate__dict', d)
	# Dictionary-like access / updates
	def __getitem__(self, name):
		value = self.__dict[name]
		if isinstance(value, dict):  # recursively view sub-dicts as objects
			value = Dictate(value)
		return value

	def __setitem__(self, name, value):
		self.__dict[name] = value
	def __delitem__(self, name):
		del self.__dict[name]

	# Object-like access / updates
	def __getattr__(self, name):
		return self[name]

	def __setattr__(self, name, value):
		self[name] = value
	def __delattr__(self, name):
		del self[name]

	def __repr__(self):
		return "%s(%r)" % (type(self).__name__, self.__dict)
	def __str__(self):
		return str(self.__dict)	
